package com.jieli.stream.dv.running2.task;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.jieli.stream.dv.running2.R;
import com.jieli.stream.dv.running2.ui.MainApplication;
import com.jieli.stream.dv.running2.ui.service.CommunicationService;
import com.jieli.stream.dv.running2.util.AppUtils;
import com.jieli.stream.dv.running2.util.ClientManager;
import com.jieli.stream.dv.running2.util.Dbug;
import com.jieli.stream.dv.running2.util.HttpManager;
import com.jieli.stream.dv.running2.util.IConstant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.jieli.stream.dv.running2.util.IActions.ACTION_UPGRADE_FILE;
import static com.jieli.stream.dv.running2.util.IConstant.DEVICE_DESCRIPTION;
import static com.jieli.stream.dv.running2.util.IConstant.KEY_DATA;
import static com.jieli.stream.dv.running2.util.IConstant.UPDATE_PATH;
import static com.jieli.stream.dv.running2.util.IConstant.UPDATE_TYPE;
import static com.jieli.stream.dv.running2.util.IConstant.UPGRADE_SDK_TYPE;

public final class DeviceDescription extends Thread {
    private String tag = getClass().getSimpleName();
    private WeakReference<CommunicationService> mServiceRef;

    public DeviceDescription(CommunicationService service) {
        mServiceRef = new WeakReference<>(service);
    }

    @Override
    public void run() {
        super.run();
        String connectIP = ClientManager.getClient().getConnectedIP();
        if (!TextUtils.isEmpty(connectIP)) {
            String url = AppUtils.formatUrl(connectIP, IConstant.DEFAULT_HTTP_PORT, "mnt/spiflash/res/dev_desc.txt");
            Dbug.i(tag, "download url = " + url);
            HttpManager.downloadFile(url, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Dbug.w(tag, "download failed, reason = " + e.getMessage());
                    if (!call.isExecuted()) {
                        call.enqueue(this);
                    }
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Dbug.i(tag, "download code = " + response.code());
                    if (response.code() == 200) {
                        ResponseBody responseBody = response.body();
                        if (responseBody != null) {
                            byte[] bytes = responseBody.bytes();
                            if (bytes != null) {
                                //Dbug.i(tag, "download ok, desc ： " + new String(bytes));
                                String output = AppUtils.splicingFilePath(MainApplication.getApplication().getAppName(),
                                        IConstant.VERSION, null, null) + File.separator + DEVICE_DESCRIPTION;
                                OutputStream outputStream;
                                outputStream = new FileOutputStream(new File(output));
                                try {
                                    outputStream.write(bytes);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    outputStream.close();
                                }
                                if (ClientManager.getClient().isConnected()) {
                                    if (mServiceRef == null) {
                                        Dbug.e(tag, "context is null");
                                        return;
                                    }
                                    String upgradePath = AppUtils.checkUpdateFilePath(mServiceRef.get(), UPGRADE_SDK_TYPE);
                                    if (!TextUtils.isEmpty(upgradePath) && !upgradePath.equals(mServiceRef.get().getString(R.string.latest_version))) {
                                        Dbug.w(tag, "sdk upgradePath = " + upgradePath);
                                        ArrayList<String> upgradePathList = new ArrayList<>();
                                        upgradePathList.add(upgradePath);
                                        Intent intent = new Intent(ACTION_UPGRADE_FILE);
                                        Bundle bundle = new Bundle();
                                        bundle.putInt(UPDATE_TYPE, UPGRADE_SDK_TYPE);
                                        bundle.putStringArrayList(UPDATE_PATH, upgradePathList);
                                        intent.putExtra(KEY_DATA, bundle);
                                        if (mServiceRef != null && mServiceRef.get() != null)
                                            mServiceRef.get().sendBroadcast(intent);
                                    }
                                }
                            }
                        }
                    }
                    response.close();
                }
            });
        }
    }
}
